<script setup>
import {
  GetListAPI,
  AddDataAPI,
  EditDataAPI,
  GetDeiltsAPI,
  DelDataAPI,
  EnableAPI,
  StopAPI,
} from "@/api/device/inspection/plan.js";

import AddFrom from "./addForm.vue";
// vue3方法实例
const { proxy } = getCurrentInstance();
const { maintenance_plan_status } = proxy.useDict("maintenance_plan_status");

// 新增 || 修改 || 查看实例
const addFromRef = ref(null);

// 储存数据
const ruleForm = ref({});

// 按钮枚举
const btnList = ref([]);

// 各种状态及小数据
const state = reactive({
  row: [], // 选中数据
  ids: "", // 选中id
  delDisabled: false, // 多选
  examineDisabled: false, // 单选
  btnloading: false, //保存加载状态
  total: 0, // 列表总数量
  isShow: false, // 新增弹窗状态
  title: "新增", // 标题
  loading: false, // 表格加载状态
});

// 列表数据
const tabelData = ref([]);

// 查询条件
const SelectList = ref([
  { label: "计划编号", model: "patrolItemPlanCode", type: "输入框" },
  { label: "计划名称", model: "planName", type: "输入框" },
  {
    label: "状态",
    model: "status",
    type: "下拉单选",
    opt: maintenance_plan_status,
  },
]);

// 列表枚举
const column = ref([
  { label: "计划编号", prop: "patrolItemPlanCode" },
  { label: "计划名称", prop: "planName" },
  { label: "状态", prop: "status" },
  { label: "计划类型", prop: "planTypeDict" },
  { label: "计划开始时间", prop: "planStartTime" },
  { label: "计划结束时间", prop: "planEndTime" },
  { label: "创建人", prop: "createBy" },
  { label: "创建时间", prop: "createTime" },
  { label: "操作", prop: "x" },
]);

// 查询条件 分页
const query = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 初始化按钮
const initBtn = () => {
  btnList.value = [
    {
      label: "新增",
      type: "add",
      hasPermi: "device:inspection:plan:add",
    },
    // {
    //   type: 'remove',
    //   disabled: state.multipleDis,
    //   hasPermi: 'device::plan:remove'
    // }
  ];
};
initBtn();

// 条件查询
const selectSubmit = (obj) => {
  Object.keys(obj).forEach((itemKey) => (query[itemKey] = obj[itemKey]));
  getList();
};

// 勾选列表数据时
const handleSelectionChange = ({ ids, row }) => {
  state.ids = ids;
  state.rows = row;
  state.multipleDis = !row.length;
  state.singleDis = row.length != 1;
  initBtn();
};
handleSelectionChange({ ids: [], row: [] });

// 新增弹窗
const addDic = () => {
  state.title = "新增";
  state.isShow = true;
};

// 修改弹窗
const editDic = async (id) => {
  state.title = "修改";
  proxy.loading("请求中，请稍后");
  try {
    const { data: res } = await GetDeiltsAPI(id);
    ruleForm.value = res;
    state.isShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 查看弹窗
const seeDic = async (id) => {
  state.title = "查看";
  proxy.loading("请求中，请稍后");
  try {
    const { data: res } = await GetDeiltsAPI(id);
    ruleForm.value = res;
    state.isShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 新增提交后台
const addSub = async () => {
  const result = await addFromRef.value.submit();
  if (!result) return;
  state.btnloading = true;
  try {
    await AddDataAPI(result);
    getList();
    close();
    proxy.successMsg("新增成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 修改提交后台
const editSub = async () => {
  const result = await addFromRef.value.submit();
  if (!result) return;
  state.btnloading = true;
  try {
    await EditDataAPI(result);
    getList();
    close();
    proxy.successMsg("修改成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 删除
const remove = async (id) => {
  const isif = await proxy.DelMessageBox();
  if (!isif) return;
  proxy.loading("删除中，请稍后");
  try {
    await DelDataAPI(id);
    getList();
    close();
    proxy.successMsg("删除成功！");
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 启用
const enableDic = async (id) => {
  const isif = await proxy.MessageBox('是否启用"计划编号"计划？');
  if (!isif) return;
  proxy.loading("启用中，请稍后");
  try {
    await EnableAPI(id);
    proxy.successMsg("启用成功！");
    getList();
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 停用
const stopDic = async (id) => {
  const isif = await proxy.MessageBox('是否停用"计划编号"计划？');
  if (!isif) return;
  proxy.loading("停用中，请稍后");
  try {
    await StopAPI(id);
    getList();
    proxy.successMsg("停用成功！");
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 弹窗取消
const close = () => {
  state.isShow = false;
  ruleForm.value = false;
};

// 获取列表数据
const getList = async () => {
  state.loading = true;
  try {
    const res = await GetListAPI(query);
    state.total = res.total;
    tabelData.value = res.rows;
  } catch (err) {
    console.error(err);
  } finally {
    state.loading = false;
  }
};
getList();
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <p-button :list="btnList" @add="addDic" @remove="batchRemove" />
      <p-table
        :loading="state.loading"
        keyId="id"
        :column="column"
        :data="tabelData"
        @change="handleSelectionChange"
        :total="state.total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      >
        <template #columnCell="{ column, record }">
          <p-dictTag
            v-if="column.prop == 'status'"
            :options="maintenance_plan_status"
            :value="record.status"
          />
          <p-operate
            v-if="column.prop == 'x'"
            :list="[
              {
                icon: 'Edit',
                emit: 'edit',
                text: '修改',
                type: 'primary',
                hasPermi: 'device:inspection:plan:edit',
                disabled: record.status != '2',
              },
              {
                icon: 'Delete',
                emit: 'remove',
                text: '删除',
                type: 'danger',
                hasPermi: 'device:inspection:plan:remove',
                disabled: record.status != '2',
              },
              {
                icon: 'Search',
                emit: 'look',
                text: '查看',
                type: 'primary',
                hasPermi: 'device:inspection:plan:query',
              },
              {
                icon: '',
                emit: 'enable',
                text: '启用',
                type: 'primary',
                disabled:
                  record.status == 1 ||
                  record.status == 4 ||
                  record.status == 5,
                hasPermi: 'device:inspection:plan:enable',
              },
              {
                icon: '',
                emit: 'deactivate',
                text: '停用',
                type: 'primary',
                disabled:
                  record.status == 2 ||
                  record.status == 3 ||
                  record.status == 4,
                hasPermi: 'device:inspection:plan:deactivate',
              },
            ]"
            @edit="editDic(record.id)"
            @remove="remove(record.id)"
            @look="seeDic(record.id)"
            @enable="enableDic(record.id)"
            @deactivate="stopDic(record.id)"
          />
        </template>
      </p-table>
    </el-card>
    <!-- 新增 || 修改 || 查看弹框 -->
    <p-dialog
      v-model="state.isShow"
      @ok="state.title == '新增' ? addSub() : editSub()"
      :title="state.title"
      @close="close"
      width="60%"
    >
      <template #body>
        <AddFrom
          ref="addFromRef"
          :is-show="state.isShow"
          :disabled="state.title == '查看'"
          :data="ruleForm"
        />
      </template>
    </p-dialog>
  </div>
</template>

<style lang="scss" scoped>
.box-card {
  margin-top: 20px;
}
</style>
